package com.tl.web04.controller;

import com.alibaba.fastjson.JSONObject;
import com.tl.web04.config.Config;
import com.tl.web04.constant.ResponseResult;
import com.tl.web04.model.entity.User;
import com.tl.web04.service.UserService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "AjaxFindUserByUserNameServlet", urlPatterns = "/ajax_findUserByUserName")
public class AjaxFindUserByUserNameServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //配置响应编码
            req.setCharacterEncoding(Config.REQ_ChARSET);
            resp.setContentType(Config.RESP_JSON_CONTENT_TYPE);
            //获取参数
            String username = req.getParameter("username");
            //获取输出
            PrintWriter out = resp.getWriter();
            //获取map
            ServletContext application = req.getServletContext();
            HashMap<String, User> userMap = (HashMap<String, User>) application.getAttribute(Config.USER_MAP);
            //调用service方法
            ResponseResult result = UserService.findUserByUserName(userMap,username);
            //向页面输出该结果
            out.print(JSONObject.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
